package com.jianye.recycdona.model.fragment.wlfare;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.jianye.recycdona.R;
import com.jianye.recycdona.control.http.CommoditOrderHttp;
import com.jianye.recycdona.control.http.UserOkHttp;
import com.jianye.recycdona.model.fragment.home.AddressListActivity;
import com.jianye.recycdona.model.fragment.home.HuishouActivity;
import com.jianye.recycdona.model.utils.TimeNumberUtils;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import static android.content.ContentValues.TAG;

public class ComOrderActivity extends AppCompatActivity implements View.OnClickListener {


    private TextView num1;
    private TextView com_order_price1, com_order_price_sum;
    private TextView com_order_yunfei;
    private TextView com_order_point;
    private TextView com_order_name;
    private TextView com_order_address;
    private Integer number;//购买件数
    private Button numadd,numremover,num2;
    private String name,specifi,price,commcarousel,freigh,pints_redeem;
    private TextView com_order_guige;
    private ImageView com_order_image;
    private double price2;
    private String phone;
    private SharedPreferences sp;
    private int Point;
    SharedPreferences sp_confg;
    private int pintsredeem;
    private String addressId;
    private String commId;
    private String parenid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_com_order);
        ActionBar actionBar=getSupportActionBar();

        if (actionBar!=null){
            actionBar.hide();
        }
        //初始化Id
        initId();
        //初始化地址
        initAddressData();
        //初始化订单信息
        initData();
    }

    @SuppressLint("SetTextI18n")
    private void initId() {
        sp_confg = getSharedPreferences("config", MODE_PRIVATE);//confi 文件名
        numadd=findViewById(R.id.numadd);
        numadd.setOnClickListener(this);
        numremover=findViewById(R.id.numremover);
        numremover.setOnClickListener(this);
        number=1;
        com_order_address=findViewById(R.id.com_order_address);//地址信息
        com_order_guige=findViewById(R.id.com_order_guige);//商品规格

        com_order_image=findViewById(R.id.com_order_image);

        num2=findViewById(R.id.num2);//数量
        num2.setText(number+"");
        num1=findViewById(R.id.num1);//数量
        num1.setText("*"+number+"");

        com_order_price1=findViewById(R.id.com_order_price1);//价格
        com_order_price_sum =findViewById(R.id.com_order_price2);//价格
        com_order_yunfei=findViewById(R.id.com_order_yunfei);//运费
        com_order_point=findViewById(R.id.com_order_point);//积分
        com_order_name=findViewById(R.id.com_order_name);//商品名称
        initAddressData();
    }


    public  int getPoint(){
        sp_confg = getSharedPreferences("config", MODE_PRIVATE);//confi 文件名
        String userphone=sp_confg.getString("phone","");
        parenid=sp_confg.getString("id","");
        try {
            UserOkHttp.getMyOkHttp().getUserinfo(userphone,sp_confg);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        return sp_confg.getInt("point",0);
    }
    //加载数据
    @SuppressLint("SetTextI18n")
    private void initData() {

        Intent intent=getIntent();

        //商品id
        commId =intent.getStringExtra("id");

        //商品name
        name=intent.getStringExtra("name");
        com_order_name.setText(name);
        //商品规格
        specifi=intent.getStringExtra("specifi");
        com_order_guige.setText("规格:"+specifi);

        //图片
        commcarousel=intent.getStringExtra("commcarousel");
        Glide.with(getApplicationContext()).load(commcarousel).into(com_order_image);

        price=intent.getStringExtra("price");//商品价格
        com_order_price1.setText("¥ "+price);
        com_order_price_sum.setText("¥ "+price);

        freigh=intent.getStringExtra("freigh");//运费
        com_order_yunfei.setText(freigh);

        pints_redeem=intent.getStringExtra("pints_redeem");//所需兑换积分
        pintsredeem=Integer.parseInt(pints_redeem);//所需兑换积分
        //请求用户当前积分值
//        String userphone=sp_confg.getString("phone","");
//        parenid=sp_confg.getString("id","");
//        try {
//            UserOkHttp.getMyOkHttp().getUserinfo(userphone,sp_confg);
//        } catch (ExecutionException | InterruptedException e) {
//            e.printStackTrace();
//        }
        Point=getPoint();
        //当前用户积分

        if (Point <50){
            com_order_point.setText("共"+Point+"，未满50，不可用");
        }else {
            com_order_point.setText("共"+Point+","+"兑换当前商品需要"+pintsredeem);
        }

        price2=Double.parseDouble(price);
    }



    //初始化地址信息
    @Override
    protected void onResume() {
        super.onResume();
        initAddressData();
    }

    //初始化地址信息
    @SuppressLint("SetTextI18n")
    private void initAddressData() {
        sp= getSharedPreferences("Address", MODE_PRIVATE);//Address 文件名
        addressId =sp.getString("id","");//地址id
        String name=sp.getString("name","");
         phone=sp.getString("phone","");
        String detai=sp.getString("detai","");
        com_order_address.setText(name+"\t"+phone+"\n"+detai);

    }
    //地址选择
    public void addressOnCli(View view) {
        startActivity(new Intent(ComOrderActivity.this, AddressListActivity.class));
    }

    //结束
    public void Finish(View view) {
        finish();
    }

    //提交订单
    public void commitOrder(View view) {
        String addressInfo=com_order_address.getText().toString().trim();
        //address_Id
        //订单号
        String ordernum=TimeNumberUtils.getLocalTrmSeqNum();
        //支付状态
        String status="待支付";
        //订单信息
        String orderInfo=name+","+specifi+"\n"+price+"\n"+commcarousel+"\n";
        //商品数量
        String comnum=num2.getText().toString().trim();
        //运费
        String yunfei=com_order_yunfei.getText().toString().trim();
        //总价
        String price=com_order_price_sum.getText().toString().trim();
        //当前时间
        String thisData= new HuishouActivity().getTime(new Date());

        if (pintsredeem>Point){
            //积分不足
            AloDialog("您的当前积分不足，无法兑换，快去做任务吧");
        }else if (addressInfo==null||addressInfo.length()<=0){
            Toast.makeText(ComOrderActivity.this,"请选择地址信息",Toast.LENGTH_LONG).show();
        }else if (parenid==null||parenid.length()<=0){
            Toast.makeText(ComOrderActivity.this,"用户Id未初始化",Toast.LENGTH_LONG).show();
        }else if (price==null||price.length()<=0){
            Toast.makeText(ComOrderActivity.this,"商品总价出错",Toast.LENGTH_LONG).show();
        }else if (thisData==null||thisData.length()<= 0){
            Toast.makeText(ComOrderActivity.this,"Time出错",Toast.LENGTH_LONG).show();
        }else {
            Log.e(TAG, "commitOrderInfo: "+addressId+"commid="+commId +addressInfo+parenid+ordernum+status+orderInfo+
                    comnum+yunfei+price+thisData);

            AlertDialog.Builder normalMoreButtonDialog = new AlertDialog.Builder(ComOrderActivity.this);
            normalMoreButtonDialog.setTitle("积分支付");
            normalMoreButtonDialog.setMessage("将扣除:"+pintsredeem+"积分");
            //设置按钮
            normalMoreButtonDialog.setPositiveButton("确定支付"
                    , new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            Log.d(TAG, "onClick: -------------------------->确定支付");

                            try {
                                String code= CommoditOrderHttp.getMyOkHttp().postCommdityOrder( addressInfo,  addressId,  thisData,  yunfei,  comnum, commId,
                                        orderInfo,  ordernum,  Integer.parseInt(parenid),  Double.parseDouble(price.replace("¥","")),  "待发货",pintsredeem+"");
                                Log.d(TAG, "commitOrder: "+code);
                            } catch (ExecutionException | InterruptedException e) {
                                e.printStackTrace();
                            }
                            dialog.dismiss();
                            AloDialog("支付成功，去查看订单吧");

                        }
                    });

            normalMoreButtonDialog.setNeutralButton("取消"
                    , new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            try {
                                String code= CommoditOrderHttp.getMyOkHttp().postCommdityOrder( addressInfo,  addressId,  thisData,  yunfei,  comnum, commId,
                                        orderInfo,  ordernum,  Integer.parseInt(parenid),  Double.parseDouble(price.replace("¥","")),  status,pintsredeem+"");
                                Log.d(TAG, "commitOrder: "+code);
                            } catch (ExecutionException | InterruptedException e) {
                                e.printStackTrace();
                            }
                            dialog.dismiss();
                        }
                    });



            normalMoreButtonDialog.create().show();

            //id=商品id
        }
    }

    //商品数量加减
    DecimalFormat df = new DecimalFormat("#0.00");
    @SuppressLint({"NonConstantResourceId", "SetTextI18n"})
    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.numremover:
                if (Point>=50){

                    double p1=Double.parseDouble(price);//单价
                    int pint=Integer.parseInt(pints_redeem);//所需兑换积分
                    if (number==1){//大于1才能减
                        Toast.makeText(ComOrderActivity.this,"最少购买一件哦",Toast.LENGTH_LONG).show();
                    }
                    if (number>1&&price2>p1){
                        --number;
                        price2=price2-p1;
                        pintsredeem=pintsredeem-pint;
                    }
                    com_order_price_sum.setText("¥ "+df.format(price2));//单价减少
                    num2.setText(number+"");
                    num1.setText("*"+number+"");
                    com_order_point.setText("共"+Point+","+"兑换当前商品需要"+pintsredeem);
                }


                break;
            case R.id.numadd:
                if (Point>=50){
                    double p2=Double.parseDouble(price);//单价
                    int pint=Integer.parseInt(pints_redeem);//所需兑换积分
                    ++number;
                    num2.setText(number+"");
                    num1.setText("*"+number+"");

                    price2=p2*number;
                    com_order_price_sum.setText("¥ "+df.format(price2));//单价增加
                    pintsredeem=pint*number;
                    com_order_point.setText("共"+Point+","+"兑换当前商品需要"+pintsredeem);
                }
                break;
        }
    }


    public  void AloDialog(String msg){
        AlertDialog.Builder normalMoreButtonDialog = new AlertDialog.Builder(ComOrderActivity.this);
        normalMoreButtonDialog.setTitle("提示");
        normalMoreButtonDialog.setMessage(msg);
        //设置按钮
        normalMoreButtonDialog.setPositiveButton("确定"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                        finish();
                    }
                });
        normalMoreButtonDialog.create().show();

    }


}